import axios, { type AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'

/**
 * API响应的基础结构
 * 所有后端接口都遵循这个格式
 */
export interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

// 创建axios实例
const request = axios.create({
  baseURL: '/app-api', // 接口地址,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    
    // 检查是否是注册请求，如果是则不添加 token
    const isRegisterRequest = config.url?.includes('/auth/register')
    
    if (token && !isRegisterRequest) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器 - 保持原有的 AxiosResponse 返回类型
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data, code, msg } = response.data
    
    if (code === 0) {
      // 返回完整的响应数据，包含 code、data、msg
      return response.data
    } else {
      ElMessage.error(msg || '请求失败')
      return Promise.reject(new Error(msg || '请求失败'))
    }
  },
  (error) => {
    console.error('响应错误:', error)
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          ElMessage.error('未授权，请重新登录')
          localStorage.removeItem('token')
          break
        case 403:
          ElMessage.error('拒绝访问')
          break
        case 404:
          ElMessage.error('请求地址出错')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(data.msg || '请求失败')
      }
    } else if (error.request) {
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 创建类型化的请求方法
const typedRequest = {
  get: <T = any>(url: string, config?: any): Promise<ApiResponse<T>> => {
    return request.get(url, config) as Promise<ApiResponse<T>>
  },
  post: <T = any>(url: string, data?: any, config?: any): Promise<ApiResponse<T>> => {
    return request.post(url, data, config) as Promise<ApiResponse<T>>
  },
  put: <T = any>(url: string, data?: any, config?: any): Promise<ApiResponse<T>> => {
    return request.put(url, data, config) as Promise<ApiResponse<T>>
  },
  delete: <T = any>(url: string, config?: any): Promise<ApiResponse<T>> => {
    return request.delete(url, config) as Promise<ApiResponse<T>>
  }
}

export default typedRequest